package com.ms.interceptor;

import com.ms.annotation.AdminOnly;
import com.ms.annotation.AdminOrOrganizerOnly;
import com.ms.entity.Manager;
import com.ms.entity.Organizer;
import com.ms.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 管理员或主办方权限拦截器
 * 检查带有 @AdminOrOrganizerOnly 注解的方法是否由管理员或主办方用户调用
 */
@Component
public class AdminOrOrganizerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否为处理方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 检查是否有AdminOrOrganizerOnly注解
        AdminOrOrganizerOnly adminOrOrganizerOnly = handlerMethod.getMethodAnnotation(AdminOrOrganizerOnly.class);
        if (adminOrOrganizerOnly == null) {
            return true;
        }

        // 获取当前用户
        Object user = UserContext.getUser();
        
        // 检查用户是否为管理员或主办方
        if (!(user instanceof Manager) && !(user instanceof Organizer)) {
            response.setStatus(403);
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write("权限不足，仅管理员或主办方可操作");
            return false;
        }

        return true;
    }
}